import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:encrypt/encrypt.dart';

class MD5 {

  static const PASSWORDKEY = "qycloud";
  static const IVSTRING = "anyuankeji";


  static String getSign(Map parameter) { 
    String secretKey = '密钥';
    var timestamp = new DateTime.now().millisecondsSinceEpoch;
    var versionNumber = 'app-v1';
    /// 存储所有key
    List<String> allKeys = [];
    parameter.forEach((key,value){
      allKeys.add(key + value);
    });
    allKeys.add('timestamp' + timestamp.toString());
    allKeys.add('versionNumber' + versionNumber);
    /// key排序
    allKeys.sort((obj1,obj2){
      return obj1.compareTo(obj2);
    });
    // /// 存储所有键值对
    // List<String> pairs = [];
    // /// 添加键值对
    // allKeys.forEach((key){
    //   pairs.add("$key${parameter[key]}");
    // });
    /// 数组转string
    String pairsString = allKeys.join("");
    /// 拼接 ABC 是你的秘钥
    String sign = secretKey + pairsString + secretKey;
    /// hash
    String signString = generateMd5(sign).toUpperCase();
    //String signString = md5.convert(utf8.encode(sign)).toString().toUpperCase();  //直接写也可以
    return signString;
  }
  /// md5加密
  static String generateMd5(String data) {
    var content = new Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    // 这里其实就是 digest.toString()
    return hex.encode(digest.bytes);
  }

  //密码加密
  static String aesPassword(String useName,String pwd,String token) {

    String string = encodeBase64(generateMd5(PASSWORDKEY)+pwd)+token;

    String ivString = generateMd5(IVSTRING).substring(0,16);

    List<int> iv = utf8.encode(ivString);

    List<int> pasKey = utf8.encode(generateMd5(PASSWORDKEY));

    final key = Key.fromBase64(base64Encode(pasKey));

    final encrypter = Encrypter(AES(key, mode: AESMode.cbc));

    final encrypted = encrypter.encrypt(string, iv: IV.fromBase64(base64Encode(iv)));

    return encrypted.base64;
  }

  /*
  * Base64加密
  */
  static String encodeBase64(String string){
    var content = utf8.encode(string);
    var digest = base64Encode(content);
    return digest;
  }

  /*
  * Base64解密
  */
  static String decodeBase64(String string){
    return String.fromCharCodes(base64Decode(string));
  }
}